//
//  AppDelegate.m
//  laziz_Merchant
//
//  Created by XMac on 16/10/21.
//  Copyright © 2016年 XMac. All rights reserved.
//

#import "AppDelegate.h"
#import "LZNewLoginViewController.h"
#import "LZHomeViewController.h"
#import "LZUserModel.h"
#import "UMMobClick/MobClick.h"
#import "TShareEventHandler.h"
#import "IQKeyboardManager.h"
#import "LZLeadingView.h"
#import "LZLeadingViewPresenter.h"
#import "extobjc.h"
#import "LZNotificationPresenter.h"
#import "JPUSHService.h"
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#endif

@import GoogleMaps;

@interface AppDelegate ()<JPUSHRegisterDelegate>
@property (nonatomic, strong) NSData *deviceToken;
@property (nonatomic, strong) LZNotificationPresenter *notificationPresenter;
@end

@implementation AppDelegate

#pragma
#pragma mark#pragma

#pragma mark config UI
-(void)configAppUI{
    /*
     ==========================================UINavigationBar appearance=================================================
     */
    // ********************** 全局设置返回按钮样式 **********************
    UINavigationBar * navigationBar = [UINavigationBar appearance];
    
    //返回按钮的箭头颜色
    
    [navigationBar setTintColor:[UIColor clearColor]];
    
    //设置返回样式图片
    
    NSString *backImageName = @"lz_back_en";
    
    if ([LZLanguageManager shareInstance].getLanguageType == LanguageType_Ar && ([[[UIDevice currentDevice] systemVersion] floatValue] >=9.0)) {
        backImageName = @"lz_back_ar";
    }
    
    UIImage *backImage = [UIImage imageNamed:backImageName];
    
    backImage = [backImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    
    navigationBar.backIndicatorImage = backImage;
    
    navigationBar.backIndicatorTransitionMaskImage = backImage;
    
    if ([[UIDevice currentDevice].systemVersion integerValue]<11) {
        //将返回按钮的文字position设置不在屏幕上显示
        [[UIBarButtonItem appearance] setBackButtonTitlePositionAdjustment:UIOffsetMake(NSIntegerMin, NSIntegerMin) forBarMetrics:UIBarMetricsDefault];
    }
    
    
    [[UINavigationBar appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor whiteColor],NSFontAttributeName:[UIFont systemFontOfSize:18]}];
    

}

-(void)configAppLeadingView {
    /*
     ==========================================Leading View=================================================
     */
    LZLeadingView *leadingView = [[LZLeadingView alloc] initWithFrame:self.window.bounds];
    [self.window.rootViewController.view addSubview:leadingView];
    
    @weakify(self)
    leadingView.dismissLeadingViewBlock = ^() {
        @strongify(self)
        [LZLeadingViewPresenter storNowVersionNum];

        [self registerAppService];
        if ([LZUserModel Instance].isLogin) {
            LZHomeViewController *homeVC = self.rootNavigationController.viewControllers.firstObject;
            [homeVC refreshMerchantInfo];
        }
    };
}

- (void)configIQKeyboard {
    [IQKeyboardManager sharedManager].enableAutoToolbar = YES;
    [IQKeyboardManager sharedManager].shouldResignOnTouchOutside = YES;
    [IQKeyboardManager sharedManager].shouldShowTextFieldPlaceholder = NO;
}

-(void)registerAppService{
    
    [GMSServices provideAPIKey:@"AIzaSyDVJkTzmzVYiQa11oS7oX93Ke1d5bfFeIg"];
}

#pragma mark - 启动设置
- (void)setRootForHomeVCWithIsShowLeadingView:(BOOL)isShow {
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle: nil];
    self.rootNavigationController = [storyboard instantiateViewControllerWithIdentifier:@"rootNavigationController"];
    self.window.rootViewController = self.rootNavigationController;
    
    self.rootNavigationController.navigationBar.translucent = NO;
    [self.rootNavigationController.navigationBar setBarTintColor:[UIColor blackColor]];
    [self.rootNavigationController setNavigationBarHidden:YES animated:YES];
    
    [self.window makeKeyAndVisible];
}

- (void)setRootForLoginVCWithIsShowLeadingView:(BOOL)isShow {
    
//    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    LZNewLoginViewController *vc = [[LZNewLoginViewController alloc] initWithNibName:@"LZNewLoginViewController" bundle:nil];
    self.rootNavigationController = [[UINavigationController alloc] initWithRootViewController:vc];
    
    self.window.rootViewController = self.rootNavigationController;
    self.rootNavigationController.navigationBar.translucent = NO;
    [self.rootNavigationController.navigationBar setBarTintColor:[UIColor blackColor]];
    [self.rootNavigationController setNavigationBarHidden:YES animated:YES];
    
    [self.window makeKeyAndVisible];
}

- (void)configMobClick {
    UMConfigInstance.appKey = @"5865bb361061d231b300083e";
    UMConfigInstance.channelId = @"App Store";
    [MobClick startWithConfigure:UMConfigInstance];
    
    //配置版本
    NSString *version = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    [MobClick setAppVersion:version];
#ifdef DEBUG
    [MobClick setLogEnabled:YES];
#endif
}

- (void)setupShareService:(NSDictionary *)launchOptions {
    
    [TShareEventHandler setupShareSDK:launchOptions];
}



#pragma mark - config JPush
- (void)configJPushWithOptions:(NSDictionary *)launchOptions {
    
    JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
    entity.types = JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound;
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        //可以添加自定义categories
        if ([[UIDevice currentDevice].systemVersion floatValue] >= 10.0) {
            NSSet<UNNotificationCategory *> *categories;
            entity.categories = categories;
        }
        else {
            NSSet<UIUserNotificationCategory *> *categories;
            entity.categories = categories;
        }
    }
    
    self.notificationPresenter = [[LZNotificationPresenter alloc] init];
    
    [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
    
    [JPUSHService setupWithOption:launchOptions appKey:@"27ee6659ea5c6816ce06cb87"
                          channel:@"AppStore"
                 apsForProduction:YES];
    
}

#pragma
#pragma mark UIApplicationDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    
    /* ❗️❗️❗️❗️❗️❗️❗️❗️ 所有需要调用权限的都需要先判断是否显示引导页，如果显示引导页，则在引导页消失后调用 ❗️❗️❗️❗️❗️❗️❗️❗️ */
    
    [[LZLanguageManager shareInstance] initUserLanguage];
    
    [self configAppUI];
    
    [self setupShareService:launchOptions];
    
    [self configMobClick];
    
    [self configIQKeyboard];
    
    
    BOOL isShowLeadingView = [LZLeadingViewPresenter isShowLeadingView];
    
    if ([LZUserModel Instance].isLogin) {
        [self setRootForHomeVCWithIsShowLeadingView:isShowLeadingView];
    }
    else {
        [self setRootForLoginVCWithIsShowLeadingView:isShowLeadingView];
    }
    
    if (isShowLeadingView) {
        [self configAppLeadingView];
    }
    else {
        [self registerAppService];
        [self configJPushWithOptions:launchOptions];
    }

    return YES;
}


- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
//   [application setApplicationIconBadgeNumber:0];
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
//    [application setApplicationIconBadgeNumber:0];
//    [application cancelAllLocalNotifications];
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

#pragma mark - JPush 相关
- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    
    DLog(@"%@", [NSString stringWithFormat:@"Device Token: %@", deviceToken]);
    DLog(@"🌂🌂userid🌂🌂 = %@",[LZUserModel Instance].userId)
    [JPUSHService registerDeviceToken:deviceToken];
    self.deviceToken = deviceToken;
    if ([LZUserModel Instance].userId.length > 0) {
        [LZNotificationPresenter setNotificationAlias:[LZUserModel Instance].userId];
    }
}

- (void)application:(UIApplication *)application
didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    DLog(@"did Fail To Register For Remote Notifications With Error: %@", error);
}

#if __IPHONE_OS_VERSION_MAX_ALLOWED > __IPHONE_7_1
- (void)application:(UIApplication *)application
didRegisterUserNotificationSettings:
(UIUserNotificationSettings *)notificationSettings {
}

// Called when your app has been activated by the user selecting an action from
// a local notification.
// A nil action identifier indicates the default action.
// You should call the completion handler as soon as you've finished handling
// the action.
- (void)application:(UIApplication *)application
handleActionWithIdentifier:(NSString *)identifier
forLocalNotification:(UILocalNotification *)notification
  completionHandler:(void (^)())completionHandler {
}

// Called when your app has been activated by the user selecting an action from
// a remote notification.
// A nil action identifier indicates the default action.
// You should call the completion handler as soon as you've finished handling
// the action.
- (void)application:(UIApplication *)application
handleActionWithIdentifier:(NSString *)identifier
forRemoteNotification:(NSDictionary *)userInfo
  completionHandler:(void (^)())completionHandler {
}
#endif

- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo {
    // iOS6及以下系统，收到通知
    [JPUSHService handleRemoteNotification:userInfo];
}

- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo
fetchCompletionHandler:
(void (^)(UIBackgroundFetchResult))completionHandler {
    
    // iOS7及以上系统，收到通知
    [JPUSHService handleRemoteNotification:userInfo];
    completionHandler(UIBackgroundFetchResultNewData);
}

#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#pragma mark- JPUSHRegisterDelegate

// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler {
    // Required
    NSDictionary * userInfo = notification.request.content.userInfo;
    
//    NSInteger badgeCount = [userInfo[@"aps"][@"badge"] integerValue];
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
    [self.notificationPresenter dealNotificationWhenAPPInDeskWithInfo:userInfo];
    
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
    }
    completionHandler(UNNotificationPresentationOptionAlert); // 需要执行这个方法，选择是否提醒用户，有Badge、Sound、Alert三种类型可以选择设置
}
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {
    
    // Required
    NSDictionary * userInfo = response.notification.request.content.userInfo;
//    NSInteger badgeCount = [userInfo[@"aps"][@"badge"] integerValue];
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
    
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        //各种推送类型判断
        
        [self.notificationPresenter dealNotificationWithDictionary:userInfo];
        
        [JPUSHService handleRemoteNotification:userInfo];
    }
    completionHandler();  // 系统要求执行这个方法
}
#endif


@end
